package com.liu.service.impl;


import com.liu.entity.Order;
import com.liu.error.BusinessException;
import com.liu.error.EmBusinessError;
import com.liu.mapper.OrderMapper;
import com.liu.service.GoodsService;
import com.liu.service.OrderService;
import com.liu.service.StockService;
import com.liu.vo.GoodsDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.LongAdder;

/**
 * 订单service
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderMapper orderDOMapper;

    @Autowired
    private StockService stockService;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final LongAdder longAdder = new LongAdder();

    @Override
    @Transactional
    public String createOrder(Long userId, Long goodsId, Long activityId, Integer amount, String orderNo) throws BusinessException {

        GoodsDetailVo goodsDetailVo = goodsService.getGoodsByIdInCache(goodsId);
        if (goodsDetailVo == null) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "商品信息不存在");
        }

        //2.落单减库存
        boolean result = stockService.decreaseStock(goodsId, amount);
        if (!result) {
            throw new BusinessException(EmBusinessError.STOCK_NOT_ENOUGH);
        }

        //3.订单入库
        Order order = new Order();
        order.setUserId(userId);
        order.setGoodsId(goodsId);
        order.setAmount(amount);
        if (activityId != null) {
            order.setGoodsPrice(goodsDetailVo.getActivityVo().getActivityGoodsPrice());
        } else {
            order.setGoodsPrice(goodsDetailVo.getPrice());
        }
        order.setActivityId(activityId);
        order.setOrderPrice((new BigDecimal(goodsDetailVo.getPrice()).multiply(new BigDecimal(amount))).doubleValue());

        //生成交易流水号,订单号
        order.setId(orderNo);

        orderDOMapper.insertSelective(order);

        //加上商品的销量
        goodsService.increaseSales(activityId, amount);

        redisTemplate.opsForValue().set(orderNo, 1);

        //4.返回前端
        return "success";
    }

    public String generateOrderNo() {
        //订单号有22位
        StringBuilder sb = new StringBuilder();
        //前16位为时间信息，年月日时分秒
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        sb.append(sdf.format(new Date()));
        //中间6位为自增序列
        //获取当前sequence
        longAdder.increment();
        long longValue = longAdder.longValue();
        sb.append(String.format("%06d", longValue));
        //最后2位为分库分表位,暂时写死
        sb.append("00");

        if (longValue == 1000000L) {
            longAdder.reset();
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(String.format("https://ennvmppre.enn.cn:4443/ServiceEngine/rest/ennProjectService/getSGTask?proid=%s&userid=8161&gid=%s",116491,null));
    }
}
